<template>
	<view class="page">
		<!-- 预约进度 -->
		<u-sticky>
			<view class="step-bar">
				<u-steps current="0" activeColor="#32C59A">
					<u-steps-item title="预约服务"></u-steps-item>
					<u-steps-item title="在线支付"></u-steps-item>
					<u-steps-item title="待服务"></u-steps-item>
					<u-steps-item title="服务中"></u-steps-item>
					<u-steps-item title="服务完成"></u-steps-item>
				</u-steps>
			</view>
		</u-sticky>
		<!-- 服务内容 -->
		<view class="service-content">
			<view class="service-type">{{ serveData.serviceName || '' }}{{ serveData.subtitle || '' }}</view>
			<view class="more" @click="showDetail()">
				<view class="content">服务内容</view>
				<image class="service-icon" src="/static/images/ic_next.png"></image>
			</view>
		</view>
		<!-- 服务参数 -->
		<view class="treatment-list">
			<view v-if="config.isVisitingHospital == 1" class="treatment-item" @click="chooseHospital()">
				<view class="treatment-title">所在医院</view>
				<view class="treatment-info">
					<view class="treatment-tip" :class="hospital ? 'active' : ''">
						{{ hospital ? hospital.hospitalName : '请选择所在医院' }}
					</view>
					<image class="service-icon" src="/static/images/ic_next.png"></image>
				</view>
			</view>
			<view v-if="config.isEscort == 1" class="treatment-item" @click="chooseEscort()">
				<view class="treatment-title">陪诊师</view>
				<view class="treatment-info">
					<view class="treatment-tip" :class="escort ? 'active' : ''">{{ escort ? escort.name : '请选择陪诊师（非必选）' }}</view>
					<image class="service-icon" src="/static/images/ic_next.png"></image>
				</view>
			</view>
			<view v-if="config.isEscort == 1 && config.isTreatmentTime == 1 && escort" class="treatment-item"
				@click="selectBookDatetime()">
				<view class="treatment-title">服务时间</view>
				<view class="treatment-info">
					<view class="treatment-tip" :class="params.treatmentTime ? 'active' : ''">
						{{ params.treatmentTime || '请选择服务时间' }}
					</view>
					<image class="service-icon" src="/static/images/ic_next.png"></image>
				</view>
			</view>
			<view v-else-if="config.isTreatmentTime == 1" class="treatment-item" @click="showTime = true">
				<view class="treatment-title">服务时间</view>
				<view class="treatment-info">
					<view class="treatment-tip" :class="params.treatmentTime ? 'active' : ''">
						{{ params.treatmentTime || '请选择服务时间' }}
					</view>
					<image class="service-icon" src="/static/images/ic_next.png"></image>
				</view>
			</view>
			<view v-if="config.isPatient == 1" class="treatment-item" @click="choosePatient()">
				<view class="treatment-title">服务对象</view>
				<view class="treatment-info">
					<view class="treatment-tip" :class="patient ? 'active' : ''">{{ patient ? patient.name : '请选择服务对象' }}</view>
					<image class="service-icon" src="/static/images/ic_next.png"></image>
				</view>
			</view>
			<view v-if="config.isReceivingInformation == 1" class="treatment-item" @click="chooseAddress()">
				<view class="treatment-title">收件信息</view>
				<view class="treatment-info">
					<view class="treatment-tip" :class="address ? 'active' : ''">{{ address | showAddress }}</view>
					<image class="service-icon" src="/static/images/ic_next.png"></image>
				</view>
			</view>
			<view v-if="config.isPickUpAddress == 1" class="treatment-item">
				<view class="treatment-title">服务地址</view>
				<input class="treatment-tip" v-model="params.serviceAddress" placeholder-style="font-size:28rpx"
					placeholder="请填写服务地址" type="text" />
			</view>
			<view v-if="config.isContactNumber == 1" class="treatment-item">
				<view class="treatment-title">联系电话</view>
				<input class="treatment-tip" v-model="params.telephone" placeholder-style="font-size:28rpx"
					placeholder="请填写联系电话" type="number" />
			</view>
		</view>
		<!-- 服务需求 -->
		<view v-if="config.isServiceRequirements == 1" class="service-requirement">
			<view class="requirement-title">服务需求</view>
			<textarea class="textarea" v-model="params.serviceRequirements" maxlength="-1" placeholder-style="color:#C3C3C3"
				placeholder="请简单描述您的就诊科室..."></textarea>
		</view>
		<!-- 协议相关 -->
		<view class="user-agreement">
			<view @click="isChecked = !isChecked">
				<image class="agreement-icon" v-if="isChecked" src="/static/images/selected@3x.png"></image>
				<image class="agreement-icon" v-else src="/static/images/NotselectedXXD@3x.png"></image>
			</view>
			<view class="agreement-text">
				我已阅读并同意
				<text @click="to('/pages/other/article/article?type=6')">《用户协议》</text>
				和
				<text @click="to('/pages/other/article/article?type=4')">《隐私政策》</text>
			</view>
		</view>
		<view class="order-btn" @click="sureOrder()">确认下单（支付{{ serveData.price || 0 }}元）</view>
		<!-- 服务时间选择器 -->
		<u-datetime-picker :show="showTime" :minDate="minDate" :maxDate="maxDate" mode="datetime" @confirm="confirmTime"
			@cancel="showTime = false"></u-datetime-picker>
		<!-- 选择陪诊师可预约时间 -->
		<book-datetime ref="popDatetime" @ok="confrimBookDatetime"></book-datetime>
		<!-- 服务内容 -->
		<u-modal :show="showContent" title="服务内容" confirmText="知道了" @confirm="showContent = false">
			<scroll-view scroll-y style="max-height: 50vh;"><mp-html
					:content="serveData.serviceDetails"></mp-html></scroll-view>
		</u-modal>
	</view>
</template>

<script>
	import BookDatetime from '@/components/book-datetime/book-datetime.vue';
	import utils from '@/utils/index.js';
	import {
		getHospitalDetails,
		getEscortDetail,
		getServiceItemsById,
		reservationService,
		getPayParams
	} from '@/apis/request.js';

	export default {
		components: {
			BookDatetime
		},
		data() {
			return {
				city: {
					id: 350200,
					title: '厦门市'
				},
				isChecked: false,
				showTime: false,
				showContent: false,
				minDate: null,
				maxDate: null,
				id: '',
				serveData: {},
				hospital: null,
				escort: null,
				patient: null,
				address: null,
				config: {},
				params: {
					cityId: '',
					addressId: '',
					escortId: '',
					hospitalId: '',
					patientId: '',
					serviceAddress: '',
					serviceId: '',
					serviceRequirements: '',
					telephone: '',
					treatmentTime: '',
					workingCalendarId: ''
				},
				timer: null,
				channel: ''
			};
		},
		filters: {
			showAddress(address) {
				if (address) {
					return `${address.provinceName}${address.cityName}${address.areaName}${address.address}`;
				} else {
					return '请选择收件信息';
				}
			}
		},
		onLoad(options) {
			this.id = options.id;
			this.city = uni.getStorageSync('city') || {};
			this.channel = options.channel
			this.params.channel = options.channel
			this.getDetail();
			//如果有医院ID说明是从医院进入默认要带上医院信息
			if (options.hospitalId) {
				this.getHospitalById(options.hospitalId);
			}
			//如果有陪诊师ID说明从陪诊师进入默认要带上陪诊师
			if (options.escortId) {
				this.getEscortById(options.escortId);
			}
			//如果有预约时间需要带上预约的时间
			if (options.workingCalendarId) {
				this.params.workingCalendarId = options.workingCalendarId;
			}
			if (options.treatmentTime) {
				this.params.treatmentTime = options.treatmentTime;
			}
			//进行全局事件监听注册
			uni.$on('selectHospital', hospital => {
				this.hospital = hospital;
				this.params.hospitalId = hospital.id;
			});
			uni.$on('selectEscort', escort => {
				this.escort = escort;
				this.params.escortId = escort.id;
			});
			uni.$on('selectDatetime', bookDatetime => {
				this.params.workingCalendarId = bookDatetime.workingCalendarId;
				this.params.treatmentTime = bookDatetime.treatmentTime;
			});
			uni.$on('selectPatient', patient => {
				this.patient = patient;
				this.params.patientId = patient.id;
			});
			uni.$on('selectAddress', address => {
				this.address = address;
				this.params.addressId = address.id;
			});
		},
		onUnload() {
			//解除全局事件监听
			uni.$off('selectHospital');
			uni.$off('selectEscort');
			uni.$off('selectDatetime');
			uni.$off('selectPatient');
			uni.$off('selectAddress');
		},
		methods: {
			/**
			 * 获取服务详情信息
			 */
			getDetail() {
				getServiceItemsById({
					cityId: this.city.id,
					id: this.id
				}).then(res => {
					this.serveData = res || {};
					this.config = this.serveData.serviceCategory || {};
					if (this.config.isTreatmentTime == 1) {
						//服务时间的最大最小可选择值
						const nowTime = new Date().getTime();
						this.minDate = nowTime + 2 * 60 * 60 * 1000;
						this.maxDate = nowTime + 5 * 24 * 60 * 60 * 1000;
					}
				});
			},
			/**
			 * 根据医院ID获取医院数据
			 * @param {String} hospitalId 医院ID
			 */
			getHospitalById(hospitalId) {
				getHospitalDetails({
					hospitalId
				}).then(res => {
					this.hospital = res;
					this.params.hospitalId = hospitalId;
				});
			},
			/**
			 * 根据陪诊师ID获取陪诊师信息
			 * @param {String} escortId 陪诊师ID
			 */
			getEscortById(escortId) {
				getEscortDetail({
					escortId
				}).then(res => {
					this.escort = res;
					this.params.escortId = escortId;
				});
			},
			/**
			 * 显示服务详情
			 */
			showDetail() {
				this.showContent = true;
			},
			/**
			 * 选择陪诊师
			 */
			chooseEscort() {
				let specification = this.serveData.specification;
				let isTreatmentTime = this.serveData.serviceCategory.isTreatmentTime; //就诊时间 0否 1是
				uni.navigateTo({
					url: `/pages/servePages/chooseChaperone?isSelect=true&specification=${specification}&isTreatmentTime=${isTreatmentTime}`
				});
			},
			/**
			 * 选择就诊人
			 */
			choosePatient() {
				uni.navigateTo({
					url: '/pages/servePages/patientVisitor?isSelect=true'
				});
			},
			/**
			 * 选择服务时间
			 */
			confirmTime(e) {
				this.showTime = false;
				this.params.treatmentTime = utils.convertTimeType(e.value);
			},
			/**
			 * 选择可预约时间
			 */
			selectBookDatetime() {
				if (this.escort) {
					this.$refs.popDatetime.open(this.escort.id);
				} else {
					this.$Toast('请先选择陪诊师');
				}
			},
			/**
			 * 确认可预约时间
			 * @param {Object} e 选择的可预约时间数据
			 */
			confrimBookDatetime(e) {
				this.params.workingCalendarId = e.workingCalendarId;
				this.params.treatmentTime = e.treatmentTime;
			},
			/**
			 * 选择收件信息
			 */
			chooseAddress() {
				uni.navigateTo({
					url: '/pages/other/address/address?type=1'
				});
			},
			/**
			 * 用户协议 隐私协议
			 * @param {Object} type 协议类型：6用户协议、4隐私政策
			 */
			to(url) {
				uni.navigateTo({
					url
				});
			},
			/**
			 * 选择医院列表
			 */
			chooseHospital() {
				uni.navigateTo({
					url: '/pages/IndexPages/hospitalList?isSelect=true'
				});
			},
			/**
			 * 确认下单
			 */
			sureOrder() {
				if (!this.isChecked) {
					this.$Toast('请先阅读并同意协议');
					return;
				}
				if (this.config.isVisitingHospital == 1 && !this.hospital) {
					this.$Toast('请选择所在医院');
					return;
				}
				// 陪诊师非必选
				// if (this.config.isEscort == 1 && !this.escort) {
				// 	this.$Toast('请选择陪诊师');
				// 	return;
				// }
				if (this.config.isTreatmentTime == 1 && !this.params.treatmentTime) {
					this.$Toast('请选择就诊时间');
					return;
				}
				if (this.config.isPatient == 1 && !this.patient) {
					this.$Toast('请选择服务对象');
					return;
				}
				if (this.config.isReceivingInformation == 1 && !this.address) {
					this.$Toast('请选择收件信息');
					return;
				}
				if (this.config.isPickUpAddress == 1 && !this.params.serviceAddress) {
					this.$Toast('请填写服务地址');
					return;
				}
				if (this.config.isContactNumber == 1 && !this.params.telephone) {
					this.$Toast('请填写联系电话');
					return;
				}
				if (!utils.checkMobile(this.params.telephone)) {
					this.$Toast('请填写正确的联系电话');
					return;
				}
				this.params.serviceId = this.id;
				this.params.cityId = this.city.id;
				if (this.timer) clearTimeout(this.timer);
				this.timer = setTimeout(() => {
					reservationService(this.params).then(res => {
						//预约成功，进行支付操作
						if (res.isPay == 1) {
							this.requestPay(res);
						} else {
							this.$Toast('订单创建成功');
							uni.navigateBack();
						}
					});
				}, 1000);
			},
			/**
			 * 请求支付
			 * @param {Object} order 订单数据
			 */
			requestPay(order) {
				let payType = 2;

				// #ifdef APP-PLUS
				payType = 1;
				// #endif

				getPayParams({
					orderId: order.orderId,
					payType: payType,
					source: 1,
					totalAmount: order.payAmount
				}).then(res => {
					//console.log('res', res);
					this.callPay(res.wxPayRequest || {});
				}).catch(err => {
					console.error(err);
					this.$Toast('发起支付失败，请重试！');
				});
			},
			/**
			 * 发起支付请求
			 * @param {Object} config 支付配置
			 */
			callPay(config) {
				console.log(config);
				// #ifdef MP-WEIXIN
				uni.requestPayment({
					provider: 'wxpay',
					timeStamp: config.timeStamp,
					nonceStr: config.nonceStr,
					package: config.packageValue,
					signType: config.signType,
					paySign: config.paySign,
					success: res => {
						uni.reLaunch({
							url: '/pages/mine/myOrder?current=2'
						});
					},
					fail: err => {
						console.error('fail:' + JSON.stringify(err));
						this.$Toast('支付失败');
						uni.reLaunch({
							url: '/pages/mine/myOrder?current=1'
						});
					}
				});
				// #endif

				// #ifdef APP-PLUS
				uni.requestPayment({
					provider: 'wxpay',
					orderInfo: {
						appid: config.appId,
						noncestr: config.nonceStr,
						package: config.packageValue,
						partnerid: config.partnerId,
						prepayid: config.prepayId,
						timestamp: config.timeStamp,
						sign: config.sign
					},
					success: res => {
						uni.reLaunch({
							url: '/pages/mine/myOrder?current=2'
						});
					},
					fail: err => {
						console.error('fail:' + JSON.stringify(err));
						this.$Toast('支付失败');
						uni.reLaunch({
							url: '/pages/mine/myOrder?current=1'
						});
					}
				});
				// #endif
			}
		}
	};
</script>

<style scoped lang="scss">
	.page {
		background-color: #f2f2f2;
		height: 100%;
		min-height: 100vh;
		padding-bottom: 36rpx;

		.step-bar {
			background-color: #fff;
			padding: 30rpx 50rpx 40rpx 50rpx;
			border-bottom: 1upx solid #f2f2f2;
		}

		.service-content {
			margin-top: 20rpx;
			background-color: #fff;
			padding: 30rpx;
			display: flex;
			align-items: center;
			justify-content: space-between;

			.service-type {
				font-size: 30rpx;
				width: 500rpx;
				overflow: hidden;
				text-overflow: ellipsis;
				white-space: nowrap;
			}

			.more {
				display: flex;
				align-items: center;

				.content {
					color: #999999;
					font-size: 28rpx;
				}

				.service-icon {
					margin-left: 8rpx;
					height: 26rpx;
					width: 16rpx;
				}
			}
		}

		.treatment-list {
			margin-top: 20rpx;
			background-color: #fff;

			.treatment-item {
				padding: 30rpx;
				border-bottom: 2rpx solid #e8e8e8;
				display: flex;
				justify-content: space-between;
				align-items: center;

				.treatment-title {
					flex-shrink: 0;
					font-size: 30rpx;
				}

				.treatment-info {
					display: flex;
					align-items: center;

					.treatment-tip {
						color: #999999;
						font-size: 28rpx;
						overflow: hidden;
						text-overflow: ellipsis;
						white-space: nowrap;

						&.active {
							color: #333333;
						}
					}

					.service-icon {
						flex-shrink: 0;
						margin-left: 8rpx;
						height: 26rpx;
						width: 16rpx;
					}
				}

				input {
					flex: 1;
					text-align: right;
				}
			}
		}

		.service-requirement {
			margin-top: 20rpx;
			background-color: #fff;
			padding: 30rpx;

			.requirement-title {
				font-size: 30rpx;
				padding-bottom: 16rpx;
			}

			.textarea {
				width: 100%;
				height: 250rpx;
				font-size: 28rpx;
			}
		}

		.user-agreement {
			margin: 60rpx 130rpx 20rpx 130rpx;
			display: flex;
			align-items: center;

			.agreement-icon {
				width: 24rpx;
				height: 24rpx;
			}

			.agreement-text {
				margin-left: 10rpx;
				font-size: 22rpx;
				color: #6e7a94;

				text {
					color: #2074f3;
				}
			}
		}

		.order-btn {
			width: 690rpx;
			height: 88rpx;
			line-height: 88rpx;
			text-align: center;
			font-size: 30rpx;
			color: #ffff;
			background-color: #32C59A;
			border-radius: 44rpx;
			margin: 0 auto;
		}
		
		.modal-footer {
			display: flex;
			gap: 20px;
		}
	}
</style>